package org.design.environmentprotection.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;

import org.design.environmentprotection.application.MyApplication;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.text.DecimalFormat;

/**
 * Author by naqiang, Date on 2019\2\18 0018.
 * PS: Not easy to write code, please indicate.
 */
public class StorageUtil {

    /**
     * 获取外置卡（可拆卸的）的目录。 Environment.getExternalStorageDirectory()获取的目录，有可能是内置卡的。
     * 在高版本上，能访问的外置卡目录只能是/Android/data/{package}。
     */
    public static String getAppRootOfSdCardRemovable() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }
        String mypath = null;
        /**
         * 这一句取的还是内置卡的目录。
         * /storage/emulated/0/Android/data/com.newayte.nvideo.phone/cache
         * 神奇的是，加上这一句，这个可移动卡就能访问了。 猜测是相当于执行了某种初始化动作。
         */
        StorageManager mStorageManager = (StorageManager) MyApplication.getContext().getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                if ((Boolean) isRemovable.invoke(storageVolumeElement)) {
                    mypath = path;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("/dev/null".equals(mypath)) {
            return null;
        }
        return mypath;
    }

    /**
     * 获取sd卡总容量
     *
     * @param path
     * @return
     */
    @SuppressLint("NewApi")
    public static String getSdTotalSize(File path) {
        String size1 = null;
        if (path != null & Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File aPath = path;
            StatFs sf = new StatFs(aPath.getPath());
            long size = sf.getBlockSizeLong();
            long total = sf.getBlockCountLong();
            long available = sf.getAvailableBlocksLong();
            DecimalFormat df = new DecimalFormat();
            df.setGroupingSize(3);
            // 总大小
            String totalSize = (size * total) / 1024 >= 1024 ? df.format((((size * total) / 1024) / 1024)) + "MB"
                    : df.format((size * total) / 1024) + "KB";
            // 可用大小
            String availableSize = (size * available) / 1024 >= 1024
                    ? df.format((((size * available) / 1024) / 1024)) + "MB"
                    : df.format((size * available) / 1024) + "KB";
            // 已使用大小
            String useSize = (size * (total - available)) / 1024 >= 1024
                    ? df.format((((size * (total - available)) / 1024) / 1024)) + "MB"
                    : df.format((size * (total - available)) / 1024) + "KB";
            size1 = totalSize;
        }
        return size1;
    }

    /**
     * 获取sd卡已用容量
     *
     * @param path
     * @return
     */
    @SuppressLint("NewApi")
    public static String getSdUsedSize(File path) {
        String size1 = null;
        if (path != null & Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File aPath = path;
            StatFs sf = new StatFs(aPath.getPath());
            long size = sf.getBlockSizeLong();
            long total = sf.getBlockCountLong();
            long available = sf.getAvailableBlocksLong();
            DecimalFormat df = new DecimalFormat();
            df.setGroupingSize(3);
            // 总大小
            String totalSize = (size * total) / 1024 >= 1024 ? df.format((((size * total) / 1024) / 1024)) + "MB"
                    : df.format((size * total) / 1024) + "KB";
            // 可用大小
            String availableSize = (size * available) / 1024 >= 1024
                    ? df.format((((size * available) / 1024) / 1024)) + "MB"
                    : df.format((size * available) / 1024) + "KB";
            // 已使用大小
            String useSize = (size * (total - available)) / 1024 >= 1024
                    ? df.format((((size * (total - available)) / 1024) / 1024)) + "MB"
                    : df.format((size * (total - available)) / 1024) + "KB";
            size1 = useSize;
        }
        return size1;
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

}
